#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:HeWenjun
# datetime:2023/11/27 15:58
# software: PyCharm
import json
import time
import requests


class AddressBook:
    def __init__(self):
        """
        访问登录接口，使用session方法实现cookie自管理
        :param 登录账号
        :param 登录密码
        """
        # 读取json文件中的登录账密
        with open('login_info.json', 'r', encoding='utf-8') as file:
            login_info = json.load(file)
            file.close()
        # 使用session方法显示cookie管理
        s = requests.session()
        # 访问登录接口
        body = {
            "type": "0",
            "username": login_info['username'],
            'password': login_info['password']
        }
        login_url = 'https://oastg.migu.cn/sysso/v2/tgts'
        re = s.post(url=login_url, data=body)
        print('登录返回:', re.text)
        s.get('https://oastg.migu.cn/portal/addressbook/list')
        self.s = s

    def get_children_org_code(self, org_code):
        """
        通过组织编号获取下一级所有的组织信息
        :param org_code: 组织的code
        :return: 1.字典格式返回所有的组织 2.列表返回所有仍然存在子级的组织code
        """
        # 空列表,存放符合条件(存在下级组织)的组织编号,用于后续遍历
        parent_org = []
        # 空字典。存放所有组织信息，组织编号为键名，组织名为键值
        full_org_dict = {}
        now_time = int(time.time())
        url = f'https://oastg.migu.cn/portal/rest/getChildOrganization?orgCode={org_code}&_={now_time}'
        re = self.s.get(url=url)
        for single_org in re.json():
            # 字典保存所有的组织信息
            full_org_dict[single_org['id']] = single_org['text']
            # 按照children值判断是否含有下级组织
            if single_org['children']:
                # 如果是，单独作为一个列表，用于后续遍历
                print(single_org['text'], ' -- 仍然包含下级组织')
                parent_org.append(single_org['id'])
        return full_org_dict, parent_org

    def get_member_by_org_code(self, org_code):
        """
        通过部门编号获取该部门下所有人员
        :param org_code: 组织的code
        :return 该组织对应的成员dict
        """
        member_dict = {}
        url = "https://oastg.migu.cn/portal/addressbook/listByOrgCode"
        header = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        }
        payload = f'pageNo=1&pageSize=1000&orgCode={org_code}&userName=&mobile=&tel=&email=&userId=&deptName=&zonghe='
        re = self.s.post(data=payload, url=url, headers=header)
        """处理接口返回参数"""
        member_list = re.json()['data']
        for member_data in member_list:
            """处理要return的字典"""
            member_employ = member_data['employeeMent']  # 组织名称
            member_id = member_data['userId']  # 用户账号
            member_dict[member_id] = member_employ
        return member_dict
